package com.lln.cjcx.service.impl;

import com.lln.cjcx.pojo.MyOkHttpClient;
import com.lln.cjcx.service.CaptchaService;
import com.lln.cjcx.util.NameUtils;
import com.lln.cjcx.value.UrlValue;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import yfdc.JavaBean;

import java.io.File;
import java.io.InputStream;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author LiLinnan
 * @version 1.0
 * @date 2020/1/14 19:02
 */

@Service
public final class CaptchaServiceImpl extends CaptchaService {
	public CaptchaServiceImpl(){
		super();
	}
	@Override
	public String getServName() {
		return "获取验证码服务";
	}

	/**
	 * @param myOkHttpClient MyOkHttpClient
	 * @param filePath       文件父路径
	 * @return 写好的文件
	 */
	@Override
	public final File getCaptcha(MyOkHttpClient myOkHttpClient, String filePath) {
		OkHttpClient client = myOkHttpClient.client;
		try {
			//创建请求
			Request captchaRequest = new Request.Builder().url(UrlValue.captchaUrl(myOkHttpClient.port)).build();
			//执行请求
			Response captchaResponse = client.newCall(captchaRequest).execute();
			//读取输入流
			if (captchaResponse.body() == null) throw new NullPointerException();//never happens
			InputStream stream = Objects.requireNonNull(captchaResponse.body()).byteStream();
			//转为byte
			byte[] bytes = IOUtils.toByteArray(stream);
			//创建一个文件
			File file = new File(filePath + NameUtils.uuidName() + ".png");
			//写出文件
			FileUtils.writeByteArrayToFile(file, bytes);
			//关闭流
			captchaResponse.close();
			return file;
		} catch (Throwable e) {
			Logger.getGlobal().log(Level.WARNING,e,()-> JavaBean.stackTrace(e));
			e.printStackTrace(System.out);
			return null;
		}
	}
}
